package org.example.struct.array;

/**
 * @author liyishan
 * @date 2024/2/1 09:26
 * @apiNote
 */

public class Test00859BuddyStrings {
    public static void main(String[] args) {
        String s = "ab";
        String goal = "ba";
        System.out.println(buddyStrings1(s, goal));
    }

    public static boolean buddyStrings1(String s, String goal) {
        if(s.length() != goal.length()){
            return false;
        }
        if(s.equals(goal)){
            int[] count = new int[26];
            for(int i = 0;i<s.length();i++){
                count[s.charAt(i) - 'a']++;
                if(count[s.charAt(i) - 'a'] >1){
                    return true;
                }
            }
            return false;
        }else{
            int first = -1,second = -1;
            for(int i = 0;i<s.length();i++){
                if(s.charAt(i) != goal.charAt(i)){
                    if(first == -1){
                        first = i;
                    }else if(second == -1){
                        second = i;
                    }else{
                        return false;
                    }
                }
            }
            return (second != -1 && s.charAt(first) == goal.charAt(second) && s.charAt(second) == goal.charAt(first));
        }
    }

    public static boolean buddyStrings(String s, String goal) {
        char[] arr = s.toCharArray();
        for(int i = 0 ;i<arr.length;i++){
            for(int j = i+1;j<arr.length;j++){
                swap(arr,i,j);
                if(new String(arr).equals(goal)){
                    return true;
                }
                swap(arr,i,j);
            }
        }
        return false;
    }

    private static void swap(char[] arr,int i,int j){
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
